package com.bloveoacom.weichi.activity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.design.widget.BottomSheetDialog;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bloveoacom.base.AppContext;
import com.bloveoacom.base.BaseListActivity;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.util.DialogUtil;
import com.bloveoacom.util.DisplayUtil;
import com.bloveoacom.util.GlideUtil;
import com.bloveoacom.util.KeyboardPatch;
import com.bloveoacom.util.KeyboardUtil;
import com.bloveoacom.util.MyClickableSpan;
import com.bloveoacom.util.NumberUtil;
import com.bloveoacom.util.PicCameraLocalUtil;
import com.bloveoacom.util.ShareUtils;
import com.bloveoacom.util.StringUtils;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.adapter.MyCommentAdapter;
import com.bloveoacom.weichi.bean.Comment2Bean;
import com.bloveoacom.weichi.bean.CommentBean;
import com.bloveoacom.weichi.bean.ItemOptionBean;
import com.bloveoacom.weichi.bean.PostDetailBean;
import com.bloveoacom.weichi.bean.RewardBean;
import com.bloveoacom.weichi.contract.PostDetailContract;
import com.bloveoacom.weichi.bean.CommentHelperModel;
import com.bloveoacom.weichi.model.PostDetailModel;
import com.bloveoacom.weichi.presenter.PostDetailPresenter;
import com.bloveoacom.weight.InputDialog;
import com.bloveoacom.weight.LlkjToolBar;
import com.bloveoacom.weight.ProgressWebView;
import com.chad.library.adapter.base.BaseQuickAdapter;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


import static com.bloveoacom.util.CalendarUtil.getTime2;
import static com.bloveoacom.util.DataUtil.DZ;
import static com.bloveoacom.util.DataUtil.PL;
import static com.bloveoacom.util.DataUtil.QD;
import static com.bloveoacom.util.DataUtil.getReward;
import static com.bloveoacom.util.DataUtil.showMsg;
import static com.bloveoacom.util.KeyboardUtil.focus;
import static com.bloveoacom.util.KeyboardUtil.showKeyboard;

/**
 * author: yjl
 * e-mail: 1271901673@qq.com
 * time  : 2018/9/20
 * desc  :
 */
public class PostDetailActivity extends BaseListActivity<PostDetailPresenter, PostDetailModel,MyCommentAdapter> implements PostDetailContract.View,View.OnClickListener,MyClickableSpan.MyClickable {
    public static final String COINID = "coin_id";
    @BindView(R.id.title_bar)
    LlkjToolBar titleBar;
    @BindView(R.id.et_count)
    EditText etCount;
    @BindView(R.id.tv_post_title)
    TextView tv_title_share;
    @BindView(R.id.layout_share)
    ConstraintLayout layoutShare;
    private ViewHolder viewHolder;
    private int coinId;
    private PostDetailBean postDetailBean;
    private InputDialog inputPasswordDialog;
    @Override
    public int getLayoutResId() {
        return R.layout.activity_post_detail;
    }
    private void showInputPasswordDialog() {
        if (inputPasswordDialog == null) {
            inputPasswordDialog = new InputDialog(this, "输入密码", "Password", true, false, R.style.MyDialogStyle);
            inputPasswordDialog.setItemClickListener(new InputDialog.ItemClickListener() {
                @Override
                public void left() {

                }

                @Override
                public void right(String content) {
                    DialogUtil.dissDialog(inputPasswordDialog);
                    mPresenter.comment(commentId, replayUserId,commentType,commentContent, content);
                }
            });
        }
        inputPasswordDialog.show();
    }

    @Override
    public void initView() {
        super.initView();
        titleBar.setToolBar("帖子详情",
                true, "", R.drawable.ic_back, true, "", R.drawable.ic_post_share);
        titleBar.setRTVisible();
        titleBar.setRightImg2(R.drawable.selector_post_collect);
       // KeyboardPatch.assistActivity(findViewById(android.R.id.content));
    }

    @Override
    protected View getViewSetTB() {
        return titleBar;
    }

    @Override
    public void initData() {
        super.initData();
        mPresenter.getCoinNewsDetail();
    }

    @Override
    protected void initSetting() {
        mAdapter = new MyCommentAdapter(R.layout.rv_item_comment,new ArrayList<CommentBean>());
        mAdapter.addHeaderView(getHeaderView());
        mAdapter.setMyClicker(this);
    }

    @Override
    public void getBundleExtras(Bundle extras) {
        coinId = extras.getInt(COINID);
    }

    @Override
    public void initListener() {
        titleBar.setRightButtonOnClickLinster(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });
        titleBar.setRightButton2OnClickLinster(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isLogin()){
                    mPresenter.goCollection(0, v.isSelected() ? 0 : 1);
                }
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                commentBean = mAdapter.getData().get(position);
                replayUserId = String.valueOf(commentBean.getUserId());
                etCount.setHint(getString(R.string.reply,commentBean.userName));
                showKeyboard(view);
            }
        });
//        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                commentBean = mAdapter.getData().get(position);
//                switch (view.getId()) {
//                    case R.id.tv_replay_comment:
//                        replayUserId = String.valueOf(commentBean.replyCommentId);
//                        etCount.setHint(getString(R.string.reply,commentBean.userName));
//                        showKeyboard(view);
//                        focus(etCount);
//                        break;
//                }
//            }
//        });

    }

    Bitmap bitmap;
    private File sharefile;
    Dialog dialog;
    private void share() {
        if (dialog == null || sharefile == null) {
            bitmap = PicCameraLocalUtil.getBitmap(layoutShare);
            sharefile = PicCameraLocalUtil.saveBitmap(mContext, bitmap, "post_detail2");
            AppContext.mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog = DialogUtil.getPicBottomDialog2(mContext, new DialogUtil.PhotoDoWhat() {
                        @Override
                        public void doone() {
                            ShareUtils.shareFriends(sharefile.getPath(), 0);
                            DialogUtil.dissDialog(dialog);
                            ToastUtil.makeShortText(mContext, "分享操作正在后台进行");
                        }

                        @Override
                        public void dotwo() {
                            ShareUtils.shareFriends(sharefile.getPath(), 1);
                            DialogUtil.dissDialog(dialog);
                            ToastUtil.makeShortText(mContext, "分享操作正在后台进行");
                        }
                        @Override
                        public void dothree() {
                            DialogUtil.dissDialog(dialog);
                        }
                    }, sharefile);
                    DialogUtil.showDialog(dialog);
                }
            }, 1000);

        } else {
            DialogUtil.showDialog(dialog);
        }
    }

    @Override
    public void newDetail(PostDetailBean bean) {
        postDetailBean = bean;
        String url = StringUtils.isEmpty(postDetailBean.getLinkUrl()) ? StringUtils.getFullUrl(postDetailBean.getUrl(), 2)
                : postDetailBean.getLinkUrl();
        viewHolder.wvContent.loadUrl(url);
        viewHolder.tvUsername.setText(postDetailBean.getUserName());
        viewHolder.tvTitle.setText(postDetailBean.getTitle());
        viewHolder.tvTime.setText(postDetailBean.getCreateTime());
        viewHolder.tvReadCount.setText(getString(R.string.read_count_value, postDetailBean.getReadNum()));
        GlideUtil.loadCircleImage(viewHolder.ivHead, StringUtils.getFullUrl(postDetailBean.headImg, 0));
        viewHolder.tvLikeCount.setText(getString(R.string.like_count_value, postDetailBean.getGiveLikeNum()));
        viewHolder.tvLikeCount.setSelected(NumberUtil.getIntByStr(postDetailBean.getIsLiked()) == 1);
        tv_title_share.setText("【" + postDetailBean.getTitle() + "】");
        titleBar.getRT2().setSelected(postDetailBean.isCollect==1);
        viewHolder.iv_attention.setSelected(Integer.valueOf(postDetailBean.isFollow)==1);
        viewHolder.tv_post_time.setText(postDetailBean.createTime);
        if(postDetailBean.getUserId().equals(UserInfoBean.getInstance().getUid())){
            viewHolder.group_user_info.setVisibility(View.GONE);
            viewHolder.tvTime.setVisibility(View.VISIBLE);
            viewHolder.tvTime.setText(postDetailBean.createTime);
        }else{
            viewHolder.group_user_info.setVisibility(View.VISIBLE);
            viewHolder.tvTime.setVisibility(View.GONE);
            viewHolder.tvTime.setText(postDetailBean.createTime);
        }
        mAdapter.setPDB(postDetailBean);
    }

    @Override
    public void comment(RewardBean bean) {
        showMsg(mContext,bean,R.drawable.ic_like_reward,getString(R.string.has_comment),PL);
        etCount.getText().clear();
        etCount.setHint("评论内容");
        mPresenter.loadFirstData(true);
        KeyboardUtil.hideSoftKeyboard(this);
    }

    @Override
    public void commentList(Comment2Bean bean) {
        loadDataComplete(bean.commentList);
        viewHolder.tv_comment_count.setText(bean.commentAllNum+"条评论");
    }

    @Override
    public void userFocus(Object bean) {
        //取消关注
        if(Integer.valueOf(postDetailBean.isFollow) == 1){
            postDetailBean.isFollow = "0";
        }else{
            //关注
            postDetailBean.isFollow = "1";

        }
        viewHolder.iv_attention.setSelected(Integer.valueOf(postDetailBean.isFollow)==1);
        ToastUtil.showCustomShort(mContext,getString(viewHolder.iv_attention.isSelected()?R.string.ok_attention:R.string.no_attention));
    }

    @Override
    public void goCollection(Object bean) {
        titleBar.getRT2().setSelected(!titleBar.getRT2().isSelected());
        ToastUtil.showCustomShort(mContext,getString(titleBar.getRT2().isSelected()?R.string.ok_collect:R.string.no_collect));
    }

    @Override
    public void collect(RewardBean bean) {
        RewardBean rewarCollectdBean = bean;
        int count = postDetailBean.getGiveLikeNum();
        if (NumberUtil.getIntByStr(postDetailBean.getIsLiked()) == 0) {
            count++;
            showMsg(mContext,bean,R.drawable.ic_like_reward,getString(R.string.has_like),DZ);
        } else {
            count--;
        }
        postDetailBean.setGiveLikeNum(count);
        postDetailBean.setIsLiked((NumberUtil.getIntByStr(postDetailBean.getIsLiked()) == 0 ? 1 : 0) + "");
        viewHolder.tvLikeCount.setText(getString(R.string.like_count_value, postDetailBean.getGiveLikeNum()));
        viewHolder.tvLikeCount.setSelected(NumberUtil.getIntByStr(postDetailBean.getIsLiked()) == 1);
    }

    @Override
    public String getNewsId() {
        return String.valueOf(coinId);
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.layout_comment_header, (ViewGroup) mRecyclerView.getParent(), false);
        viewHolder = new ViewHolder(view);
        viewHolder.tvLikeCount.setOnClickListener(this);
        viewHolder.iv_attention.setOnClickListener(this);
        return view;
    }


    static class ViewHolder {
        @BindView(R.id.wv_content)
        WebView wvContent;
        @BindView(R.id.tv_like_count)
        TextView tvLikeCount;
        @BindView(R.id.tv_read_count)
        TextView tvReadCount;
        @BindView(R.id.tv_time)
        TextView tvTime;
        @BindView(R.id.iv_head)
        ImageView ivHead;
        @BindView(R.id.iv_attention)
        ImageView iv_attention;
        @BindView(R.id.tv_username)
        TextView tvUsername;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_post_time)
        TextView tv_post_time;
        @BindView(R.id.tv_comment_count)
        TextView tv_comment_count;
        @BindView(R.id.group_user_info)
        Group group_user_info;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
    CommentBean commentBean;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (viewHolder != null && viewHolder.wvContent != null) {
            viewHolder.wvContent.destroy();
        }
    }

    private String commentContent="", replayUserId ="",commentType="0",commentId="";
    public void setCommentData(){
        commentContent = etCount.getText().toString().trim();
        if(commentBean!=null){
            commentId = String.valueOf(commentBean.getCommentId());
            commentType = "1";
            if(StringUtils.isEmpty(replayUserId)){
                replayUserId =  String.valueOf(commentBean.getUserId());
            }
        }else{
            commentId=String.valueOf(coinId);
            commentType="0";
            replayUserId = "";
        }
    }
    @Override
    @OnClick({R.id.tv_comment})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_like_count:
                if (isLogin()) {
                    int isCollect = NumberUtil.getIntByStr(postDetailBean.getIsLiked()) == 0 ? 1 : 0;
                    mPresenter.collect(String.valueOf(coinId),1,isCollect);
                }
                break;
            case R.id.tv_comment:
                if (isLogin()) {
                    setCommentData();
                    if (StringUtils.isEmpty(commentContent)) {
                        ToastUtil.makeShortText(mContext, R.string.please_input_comment_content);
                        return;
                    }
                    showInputPasswordDialog();
                }
                break;
            case R.id.iv_attention:
                if (isLogin()) {
                    mPresenter.userFocus(postDetailBean.getUserId(),(Integer.valueOf(postDetailBean.isFollow) == 1 ? 1 : 0));
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void myClickable(Object map) {
        CommentHelperModel model = (CommentHelperModel) map;
        commentBean = model.bean;
        replayUserId = model.replyId;
        if(!model.replyName.equals(UserInfoBean.getInstance().getNickName())){
            etCount.setHint(getString(R.string.reply,model.replyName));
        }else{
            etCount.setHint("评论内容");
        }
        showKeyboard(etCount);
        focus(etCount);
        ToastUtils.showShort(model.replyId);
    }

}
